#!/usr/bin/env python

import cgi
import wsgiref.handlers
import os
from google.appengine.api import users
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app

from google.appengine.api import urlfetch
import xml.etree.ElementTree as ET
import codecs

from google.appengine.api.labs import taskqueue

from db_weather_yahoo import DbWeatherYahoo
from db_city import DbCity

class WeatherYahoo(webapp.RequestHandler):
    def get(self):
        db_city_query = DbCity.all()
        for city in db_city_query:
            taskqueue.add(url='/weatherYahooTask', params={'woeid': city.woeid_weather})
    def post(self):
        pass

class WeatherYahooTask(webapp.RequestHandler):
    def post(self):
        woeid = self.request.get('woeid')
        url = "http://weather.yahooapis.com/forecastrss?w=" + woeid + "&u=c"
        result = urlfetch.fetch(url=url)
        result_xml = ET.fromstring(result.content)
        forecast = result_xml.find('channel/item/{http://xml.weather.yahoo.com/ns/rss/1.0}forecast')
        try :
            if forecast.attrib["date"]:
                def txn():
                    dbweather = DbWeatherYahoo()
                    dbweather.low = forecast.attrib["low"]
                    dbweather.high = forecast.attrib["high"]
                    #dbweather.condition_text = forecast.attrib["text"]
                    dbweather.condition_code = forecast.attrib["code"]
                    dbweather.date_yahoo = forecast.attrib["date"]
                    dbweather.woeid = woeid
                    #dbweather.city = city.name
                    #dbweather.idx = city.idx
                    dbweather.put()
                db.run_in_transaction(txn)
        except:
            self.response.out.write("woeid wrong")
            pass

    ''' just for debug
    def get(self):
        woeid = self.request.get('woeid')
        url = "http://weather.yahooapis.com/forecastrss?w=" + woeid + "&u=c"
        self.response.out.write(url)
        result = urlfetch.fetch(url=url)
        result_xml = ET.fromstring(result.content)
        forecast = result_xml.find('channel/item/{http://xml.weather.yahoo.com/ns/rss/1.0}forecast')
        try :
            if forecast.attrib["date"]:
                def txn():
                    dbweather = DbWeatherYahoo()
                    dbweather.low = forecast.attrib["low"]
                    dbweather.high = forecast.attrib["high"]
                    dbweather.condition_text = forecast.attrib["text"]
                    dbweather.condition_code = forecast.attrib["code"]
                    dbweather.date_yahoo = forecast.attrib["date"]
                    dbweather.woeid = woeid
                    #dbweather.city = city.name
                    #dbweather.idx = city.idx
                    dbweather.put()
                db.run_in_transaction(txn)
                self.response.out.write("done!!!")
        except:
            self.response.out.write("woeid wrong")
            pass
    '''

def main():
  application = webapp.WSGIApplication([('/weatherYahoo', WeatherYahoo),
                                        ('/weatherYahooTask', WeatherYahooTask),
                                        ], debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
